package com.jn.retrofit.presenter;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;

import com.jn.retrofit.common.WeakRrfHandler;
import com.jn.retrofit.contract.TestContract;
import com.jn.retrofit.utils.LogUtils;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class TestPresenter implements TestContract.ITestPresenter {
    public static final int HTTP_SUCCESS = 0;
    public static final int HTTP_FAIL = 1;

    private TestContract.ITestView mMainView;
    private Context mContext;
    private OkHttpClient mClient;

    public TestPresenter(TestContract.ITestView mMainView, Context mContext) {
        this.mMainView = mMainView;
        this.mContext = mContext;
        mClient = new OkHttpClient();
    }

    //GET 测试
    @Override
    public void get(String keyWord) {
        String url = "https://api.oioweb.cn/api/common/OneFilm";
        HttpUrl.Builder httpBuilder = HttpUrl.parse(url).newBuilder();
        //httpBuilder.addQueryParameter("text", "好");
        Request request = new Request.Builder().url(httpBuilder.build()).build();
        Call call = mClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                LogUtils.d("asdf", "onFailure");
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String body = response.body().string();
                String url = call.request().url().toString();
                LogUtils.d("asdf", "url : " + url);
                LogUtils.d("asdf", "onResponse : " + body);
                Message message = Message.obtain();
                message.obj = new String[] {body, url};
                message.what = HTTP_SUCCESS;
                mHandler.sendMessage(message);
            }
        });
    }

    //POST测试
    @Override
    public void post(String keyWord) {
        LogUtils.d("asdf", "post keyWord == " + keyWord);
        String url = "https://api.uomg.com/api/rand.img2";
        FormBody.Builder builder = new FormBody.Builder();
        // 添加POST参数
        //builder.add("keyword", keyWord);
        builder.add("format", "json");
        builder.add("sort", "二次元");

        // 构建FormBody
        FormBody formBody = builder.build();
        // 创建Request对象
        Request request = new Request.Builder()
                .url(url) // 目标URL
                .post(formBody) // 设置请求体
                .build();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Response response = mClient.newCall(request).execute();
                    if (response.isSuccessful()) {
                        String body = response.body().string();
                        LogUtils.d("asdf", "onResponse : " + body);
                        Message message = Message.obtain();
                        message.obj = new String[]{body, url};
                        message.what = HTTP_SUCCESS;
                        mHandler.sendMessage(message);
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }

    WeakRrfHandler<TestPresenter> mHandler = new WeakRrfHandler<>(Looper.getMainLooper(), this, new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            int result = msg.what;
            switch (result) {
                case HTTP_SUCCESS:
                    String[] data = (String[]) msg.obj;
                    if (data == null || data.length < 2) {
                        return false;
                    }
                    String jsonStr = data[0];
                    if (mMainView != null) {
                        mMainView.showData(jsonStr);
                    }
                    break;
                case HTTP_FAIL:
                    break;
            }
            return false;
        }
    });


}
